﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FileManagerGlobal_Library;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.BusinessLogic.FileTransferService;
using FileManager_Client.PresentationLayer.Common;
using FileManager_Client.Utility;
using System.Linq;

namespace FileManager_Client.PresentationLayer.NewUi
{
    public partial class FileManager_Form
    {
        #region Downloading File Shown Event And Init Object
        public List<DownloadingFileProgress> _downloadingFileProgresses = new List<DownloadingFileProgress>();
        private List<string> BreakDownloadingList = new List<string>(); 
        void FileManager_Form_Shown_Downloading(object sender, EventArgs e)
        {
            var breakDownloadingCollection = UserLocalFile.GetFileDownloadingBreakObject();
            var tooBarItem = ToolBar_System.Items[ToolBarItemIndex.DownloadManager];
            foreach (var fileDownloadingBreakClass in breakDownloadingCollection)
            {
                tooBarItem.LeftUpNumber++;
                var breakDownload = new DownloadingFileProgress
                                        {
                                            BeginTime = fileDownloadingBreakClass.BeginTime,
                                            CurrentState = fileDownloadingBreakClass.CurrentState,
                                            DisplaySize = fileDownloadingBreakClass.DisplaySize,
                                            FileGuid = fileDownloadingBreakClass.FileGuid,
                                            FileLocalPath = fileDownloadingBreakClass.FileLocalPath,
                                            FileName = fileDownloadingBreakClass.FileName,
                                            FileSize = fileDownloadingBreakClass.FileSize,
                                            FolderId = fileDownloadingBreakClass.FolderId,
                                            ServerPath = fileDownloadingBreakClass.ServerPath,
                                            DownloadingState = fileDownloadingBreakClass.DownloadingState
                                        };
                var downloadButton = new SimpleButton { Enabled = true, Text = "继续下载" };
                breakDownload.DownloadButton = downloadButton;
                downloadButton.Click += downloadingButton_Click;
                downloadButton.Tag = breakDownload.FileGuid;
               // var progressBar = new System.Windows.Forms.ProgressBar { Maximum = fileDownloadingBreakClass.MaxProgress, Value = fileDownloadingBreakClass.ValueProgress };
                var progressBar = new ProgressBarControl();
                progressBar.Properties.Maximum = fileDownloadingBreakClass.MaxProgress;
                progressBar.Position = fileDownloadingBreakClass.ValueProgress;
                progressBar.Properties.PercentView = true;
                progressBar.Properties.ShowTitle = true;
                breakDownload.DownloadProgressBar = progressBar;
                Olv_Downloading.AddObject(breakDownload);
                breakDownload.DownloadingClass = new List<FileInfoLocalClass>();
                foreach (var fileDownloadingBreakBlockClass in fileDownloadingBreakClass.FileDownloadingBreakBlockClasses)
                {
                    breakDownload.DownloadingClass.Add(new FileInfoLocalClass
                                                           {
                                                               FileEndOffset = fileDownloadingBreakBlockClass.FileOffset + fileDownloadingBreakBlockClass.TransferLength,
                                                               FileGuid = fileDownloadingBreakBlockClass.FileGuid,
                                                               FileOffset = fileDownloadingBreakBlockClass.FileOffset,
                                                               FileServerPath = fileDownloadingBreakBlockClass.FileServerPath,
                                                               LocalPath = fileDownloadingBreakBlockClass.LocalPath,
                                                               TransferLength = fileDownloadingBreakBlockClass.TransferLength
                                                           });
                }
                _downloadingFileProgresses.Add(breakDownload);
                foreach (var item in Olv_Downloading.Items.Cast<ListViewItem>().Where(item => string.IsNullOrEmpty(item.Name)))
                {
                    var uploadfileObj =
                        _downloadingFileProgresses.FirstOrDefault(
                            x => x.FileName.Equals(item.Text));
                    if (null == uploadfileObj) continue;
                    Olv_Downloading.AddEmbeddedControl(breakDownload.DownloadProgressBar, 2, item.Index);
                    Olv_Downloading.AddEmbeddedControl(breakDownload.DownloadButton, 5, item.Index, DockStyle.None);
                    //item.ImageIndex = 1;//ReturnImageKey(uploadfileObj.FileName);
                    item.Name = uploadfileObj.FileGuid;
                }
            }
        }
        #endregion

        #region Add File To Downloading
        private void AddDownloadingProgress(List<FileDoanloadingTemp> downloadFiles)
        {
            var startDownloadingWorker = new BackgroundWorker();
            startDownloadingWorker.DoWork += startDownloadingWorker_DoWork;
            startDownloadingWorker.RunWorkerAsync(downloadFiles);
        }

        private void SetDownloadingList(DownloadingFileProgress downloadingFileProgress)
        {
            downloadingFileProgress.DownloadingClass = new List<FileInfoLocalClass>();
            //Multiplied by 5 threads per 100mb
            var threadCount = GlobalVariable.ClientAppVariable.DownloadNumberOfThreads;
            if (downloadingFileProgress.FileSize < LowMb)
            {
                threadCount = 2;
            }
            if (downloadingFileProgress.FileSize > PerMb)
            {
                var perount = (int)(downloadingFileProgress.FileSize / PerMb);
                threadCount += perount;
                if (downloadingFileProgress.FileSize % PerMb > 0)
                    threadCount++;
            }
            var transferLength = downloadingFileProgress.FileSize / threadCount;
            var progressMax = 0;
            for (var i = 0; i < threadCount; i++)
            {
                var tempClass = new FileInfoLocalClass()
                {
                    FileOffset = i * transferLength,
                    LocalPath = downloadingFileProgress.FileLocalPath,
                    FileGuid = downloadingFileProgress.FileGuid,
                    FileServerPath = downloadingFileProgress.ServerPath
                };
                if (i + 1 == threadCount)
                    tempClass.TransferLength = (transferLength + downloadingFileProgress.FileSize % threadCount);
                else
                    tempClass.TransferLength = transferLength;
                progressMax += (int)(tempClass.TransferLength / GlobalVariable.ClientAppVariable.DownloadBlockSize);
                if (tempClass.TransferLength % GlobalVariable.ClientAppVariable.DownloadBlockSize > 0)
                    progressMax++;
                downloadingFileProgress.DownloadingClass.Add(tempClass);
            }
            downloadingFileProgress.DownloadProgressBar.Properties.Maximum = progressMax;
            downloadingFileProgress.DownloadProgressBar.Invoke((EventHandler)delegate
            {
                downloadingFileProgress.
                    DownloadProgressBar.Update();
            });
        }

        void startDownloadingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var downloadFileCollection = e.Argument as List<FileDoanloadingTemp>;
                if (null == downloadFileCollection) return;
                var tooBarItem = ToolBar_System.Items[ToolBarItemIndex.DownloadManager];
                var fileSidCollection = downloadFileCollection.Select(x => x.FileSid).ToList();
                var args = new DownlaodingCheckFilesArgs { FileSidCollectionk__BackingField = fileSidCollection.ToArray() };
                var fileInfoResult = fileService.DownloadingCheckFile(args);
                var notFindFile = new List<string>();
                var thisDownload = new List<DownloadingFileProgress>();
                foreach (var downloadingCheckFileResult in fileInfoResult.DownloadingCheckFilesk__BackingField)
                {
                    if (downloadingCheckFileResult.FileExceptionk__BackingField == FileExceptionEnum.FileNotFind)
                    {
                        notFindFile.Add(downloadingCheckFileResult.FileNamek__BackingField);
                        continue;
                    }
                    var file =
                        downloadFileCollection.FirstOrDefault(
                            x => x.FileSid.Equals(downloadingCheckFileResult.FileSidk__BackingField));
                    if (null == file) continue;
                    var filePath = Path.Combine(file.DownloadLocalPath,
                                                downloadingCheckFileResult.FileNamek__BackingField);
                    if (File.Exists(filePath))
                    {
                        var message = string.Format("文件 {0} 已经存在，是否覆盖?",
                                                    downloadingCheckFileResult.FileNamek__BackingField);
                        if (XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                            continue;
                    }
                    var downloadingFilePath = filePath + GlobalVariable.FileTempExtension;
                    if (File.Exists(downloadingFilePath))
                        File.Delete(downloadingFilePath);
                    File.Create(downloadingFilePath).Close();
                    File.Open(downloadingFilePath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite).SetLength(
                        downloadingCheckFileResult.FileSizek__BackingField);
                    //File.Create(downloadingFilePath).SetLength(downloadingCheckFileResult.FileSizek__BackingField);
                    var displaySize = Math.Round((downloadingCheckFileResult.FileSizek__BackingField / 1024.0) / 1024, 2);
                    tooBarItem.LeftUpNumber++;
                    var downloadingButton = new SimpleButton { Enabled = false, Text = "暂停下载" };
                    downloadingButton.Click += downloadingButton_Click;
                    downloadingButton.Tag = downloadingCheckFileResult.FileSidk__BackingField;
                    var progressBar = new ProgressBarControl();
                    progressBar.Properties.PercentView = true;
                    progressBar.Properties.ShowTitle = true;
                    var fileDownload = new DownloadingFileProgress
                    {
                        BeginTime = DateTime.Now,
                        CurrentState = "正在创建连接",
                        DownloadingState = DownloadingStateEnum.CreateConnectToServer,
                        DisplaySize = displaySize,
                        FileLocalPath = filePath,
                        ServerPath = downloadingCheckFileResult.FileServerPathk__BackingField,
                        FileSize = downloadingCheckFileResult.FileSizek__BackingField,
                        FolderId = file.FolderId,
                        FileGuid = downloadingCheckFileResult.FileSidk__BackingField,
                        FileName = downloadingCheckFileResult.FileNamek__BackingField,
                        DownloadButton = downloadingButton,
                        DownloadProgressBar = progressBar,
                        IsOpen = file.IsOpen
                    };

                    _downloadingFileProgresses.Add(fileDownload);
                    thisDownload.Add(fileDownload);
                    Olv_Downloading.Invoke((EventHandler)delegate
                    {
                        Olv_Downloading.AddObject(fileDownload);
                    });
                }
                Olv_Downloading.Invoke((EventHandler)delegate
                {
                    foreach (var item in Olv_Downloading.Items.Cast<ListViewItem>().Where(item => string.IsNullOrEmpty(item.Name)))
                    {
                        var downloadFileObj =
                            _downloadingFileProgresses.FirstOrDefault(
                                x => x.FileName.Equals(item.Text));
                        if (null == downloadFileObj) continue;
                        Olv_Downloading.AddEmbeddedControl(
                            downloadFileObj.DownloadProgressBar, 2, item.Index);
                        Olv_Downloading.AddEmbeddedControl(
                            downloadFileObj.DownloadButton, 5, item.Index,
                            DockStyle.None);
                        item.Name = downloadFileObj.FileGuid;
                    }
                    Olv_Downloading.Refresh();
                });
                foreach (var downloadingFileProgress in thisDownload)
                {
                    LockFiles.Add(downloadingFileProgress.FileGuid,new object());
                    SetDownloadingList(downloadingFileProgress);
                    foreach (var fileInfoLocalClass in downloadingFileProgress.DownloadingClass)
                    {
                        fileInfoLocalClass.FileEndOffset = fileInfoLocalClass.FileOffset +
                                                           fileInfoLocalClass.TransferLength;
                        var downloadingWoker = new BackgroundWorker();
                        fileInfoLocalClass.BackgroundWorker = downloadingWoker;
                        downloadingWoker.DoWork += downloadingWoker_DoWork;
                        downloadingWoker.WorkerSupportsCancellation = true;
                        downloadingWoker.RunWorkerAsync(fileInfoLocalClass);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("程序异常，请联系管理员!", GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
                LogLoader.Instance.Log.Error("startDownloadingWorker_DoWork has problem", ex);
            }
        }

        void downloadingWoker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var downloadClass = e.Argument as FileInfoLocalClass;
                if (null == downloadClass) return;
                var fileDownloadingServer = ServiceBroker.CreateFileServer();
                var backgroundWorker = (sender as BackgroundWorker);
                if (null == backgroundWorker) return;
                var fileDownload = _downloadingFileProgresses.FirstOrDefault(x => x.FileGuid.Equals(downloadClass.FileGuid));
                if (null == fileDownload) return;
                fileDownload.CurrentState = "正在下载...";
                Olv_Downloading.Invoke((EventHandler)delegate
                {
                    Olv_Downloading.RefreshObject(fileDownload);
                });
                if (fileDownload.DownloadingState != DownloadingStateEnum.Downloading)
                    fileDownload.DownloadingState = DownloadingStateEnum.Downloading;
                if (!fileDownload.DownloadButton.Enabled)
                {
                    fileDownload.DownloadButton.Invoke((EventHandler)delegate
                    {
                        fileDownload.DownloadButton.Enabled = true;
                        fileDownload.DownloadButton.Update();
                    });
                }
                var downloadFileTempPath = fileDownload.FileLocalPath +
                                           GlobalVariable.FileTempExtension;
                var fileDownloadArgs = new FileDownloadingArgs
                {
                    Offsetk__BackingField = downloadClass.FileOffset,
                    ServerPathk__BackingField = downloadClass.FileServerPath
                };
                var fileLength = downloadClass.FileEndOffset - downloadClass.FileOffset;
                var lockObj = LockFiles[downloadClass.FileGuid];
                if (lockObj == null)
                {
                    LockFiles.Add(downloadClass.FileGuid, new object());
                    lockObj = LockFiles[downloadClass.FileGuid];
                }
                while (fileLength != fileDownloadArgs.DownloadSizek__BackingField)
                {
                    fileDownloadArgs.DataLengthk__BackingField = fileLength -
                                                                 fileDownloadArgs.DownloadSizek__BackingField <=
                                                                 GlobalVariable.ClientAppVariable.DownloadBlockSize
                                                                     ? fileLength -
                                                                       fileDownloadArgs.DownloadSizek__BackingField
                                                                     : GlobalVariable.ClientAppVariable.DownloadBlockSize;
                    var fileData = fileDownloadingServer.DownloadingFile(fileDownloadArgs);
                    lock (lockObj)
                    {
                        var fileStream = new FileStream(downloadFileTempPath, FileMode.Open, FileAccess.Write,
                                                   FileShare.Write); //打开文件
                        var writer = new BinaryWriter(fileStream);
                        fileStream.Position = fileDownloadArgs.Offsetk__BackingField;
                        writer.Write(fileData.DataTransferk__BackingField);
                        writer.Close();
                        fileStream.Close();
                    }
                    var length = fileData.DataTransferk__BackingField.Length;
                    fileDownloadArgs.Offsetk__BackingField += length;
                    fileDownloadArgs.DownloadSizek__BackingField += length;
                    fileData.DataTransferk__BackingField = null;
                    downloadClass.FileOffset += length;
                    downloadClass.TransferLength -= length;
                    SetDownloadingProgress(downloadClass);
                    if (!backgroundWorker.CancellationPending) continue;
                    BreakFileDownloading(downloadClass.FileGuid);
                    e.Cancel = true;
                    break;
                }
                ServiceBroker.DisposeService(fileDownloadingServer);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("下载异常，请联系管理员!", GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
                LogLoader.Instance.Log.Error("downloadingWoker_DoWork has problem", ex);
            }
        }

        private void SetDownloadingProgress(FileInfoLocalClass fileInfoLocalClass)
        {
            var fileDownload = _downloadingFileProgresses.FirstOrDefault(x => x.FileGuid.Equals(fileInfoLocalClass.FileGuid));
            if (null != fileDownload)
            {
                fileDownload.DownloadProgressBar.Invoke((EventHandler)
                                                        delegate
                                                        {
                                                            if (fileDownload.DownloadProgressBar.Position + 1 <= fileDownload.DownloadProgressBar.Properties.Maximum)
                                                                fileDownload.DownloadProgressBar.Position += 1;
                                                            fileDownload.DownloadProgressBar.Update();
                                                            fileDownload.DownloadProgressBar.Invalidate();
                                                            if (fileDownload.DownloadProgressBar.Position != fileDownload.DownloadProgressBar.Properties.Maximum) return;
                                                            fileDownload.CurrentState = "下载完成";
                                                            Olv_Downloading.RefreshObject(fileDownload);
                                                            fileDownload.DownloadButton.Invoke(
                                                                (EventHandler)delegate
                                                                {
                                                                    fileDownload.DownloadButton.
                                                                        Text = "下载完成";
                                                                    fileDownload.DownloadButton.
                                                                        Enabled = false;
                                                                    fileDownload.DownloadButton.Update();
                                                                });
                                                            LockFiles.Remove(fileDownload.FileGuid);
                                                            var tooBarItem = ToolBar_System.Items[ToolBarItemIndex.DownloadManager];
                                                            if (tooBarItem.LeftUpNumber - 1 == 0)
                                                                tooBarItem.LeftUpNumber = 0;
                                                            else
                                                                tooBarItem.LeftUpNumber--;
                                                            Olv_Downloading.RemoveObject(fileDownload);
                                                            _downloadingFileProgresses.Remove(fileDownload);
                                                            fileService.DownloadingFileSuccess(new DownloadingSuccessArgs
                                                            {
                                                                FileSidk__BackingField = fileDownload.FileGuid,
                                                                UserIdk__BackingField = userSession.UserIdk__BackingField
                                                            });
                                                            AddDownloadLog(fileDownload);
                                                            if (File.Exists(fileDownload.FileLocalPath))
                                                                File.Delete(fileDownload.FileLocalPath);
                                                            //try
                                                            //{
                                                            //    File.Move(
                                                            //    fileDownload.FileLocalPath +
                                                            //    GlobalVariable.FileTempExtension,
                                                            //    fileDownload.FileLocalPath);
                                                            //}
                                                            //catch
                                                            //{
                                                            //}
                                                            try
                                                            {
                                                                File.Copy(fileDownload.FileLocalPath +
                                                                GlobalVariable.FileTempExtension, fileDownload.FileLocalPath, true);
                                                                File.Delete(fileDownload.FileLocalPath +
                                                                    GlobalVariable.FileTempExtension);
                                                            }
                                                            catch
                                                            {
                                                            }
                                                            
                                                            if (fileDownload.IsOpen)
                                                                Process.Start(fileDownload.FileLocalPath);
                                                        });
            }
        }
        #endregion

        #region Break Downloading Method
        private void BreakFileDownloading(string fileGuid)
        {
            BreakDownloadingList.Add(fileGuid);
            var stopNumber = BreakDownloadingList.Count(x => x.Equals(fileGuid));
            var downloadObj = _downloadingFileProgresses.FirstOrDefault(x => x.FileGuid.Equals(fileGuid));
            if(null == downloadObj)return;
            var hasDownloaded = downloadObj.DownloadingClass.Count(x => x.FileOffset == x.FileEndOffset);
            stopNumber += hasDownloaded;
            if (stopNumber != GlobalVariable.ClientAppVariable.DownloadNumberOfThreads) return;
            var fileBreak = new FileDownloadingBreakClass
                                {
                                    BeginTime = downloadObj.BeginTime,
                                    CurrentState = downloadObj.CurrentState,
                                    DisplaySize = downloadObj.DisplaySize,
                                    FileGuid = downloadObj.FileGuid,
                                    FileLocalPath = downloadObj.FileLocalPath,
                                    FileName = downloadObj.FileName,
                                    FileSize = downloadObj.FileSize,
                                    FolderId = downloadObj.FolderId,
                                    MaxProgress = downloadObj.DownloadProgressBar.Properties.Maximum,
                                    ServerPath = downloadObj.ServerPath,
                                    DownloadingState = downloadObj.DownloadingState,
                                    ValueProgress = downloadObj.DownloadProgressBar.Position,
                                    FileDownloadingBreakBlockClasses = new List<FileDownloadingBreakBlockClass>()
                                };
            foreach (var fileInfoLocalClass in downloadObj.DownloadingClass)
            {
                if (fileInfoLocalClass.FileOffset == fileInfoLocalClass.FileEndOffset) continue;
                fileBreak.FileDownloadingBreakBlockClasses.Add(new FileDownloadingBreakBlockClass
                                                                   {
                                                                       FileGuid = fileInfoLocalClass.FileGuid,
                                                                       FileOffset = fileInfoLocalClass.FileOffset,
                                                                       FileServerPath = fileInfoLocalClass.FileServerPath,
                                                                       LocalPath = fileInfoLocalClass.LocalPath,
                                                                       TransferLength = fileInfoLocalClass.TransferLength,
                                                                       FileEndOffset = fileInfoLocalClass.FileEndOffset
                                                                   });
            }
            UserLocalFile.SaveFileDownloadingBreakObject(fileBreak);
            BreakDownloadingList.RemoveAll(x => x.Equals(fileGuid));
            downloadObj.DownloadButton.Invoke((EventHandler)delegate
            {
                downloadObj.DownloadButton.Text = "继续下载";
                downloadObj.DownloadButton.Enabled = true;
                downloadObj.DownloadButton.Update();
            });
        }
        #endregion

        #region Downloading Button Event
        public void downloadingButton_Click(object sender, EventArgs e)
        {
            var fileGuid = ((SimpleButton)sender).Tag.ToString();
            var chooseObj = _downloadingFileProgresses.FirstOrDefault(x => x.FileGuid.Equals(fileGuid));
            if(null == chooseObj)return;
            switch (chooseObj.DownloadingState)
            {
                    case DownloadingStateEnum.Downloading:
                    chooseObj.CurrentState = "暂停下载....";
                    chooseObj.DownloadButton.Enabled = false;
                    chooseObj.DownloadButton.Text = "正在停止";
                    chooseObj.DownloadingState = DownloadingStateEnum.BreakDownloading;
                    chooseObj.DownloadButton.Update();
                    Olv_Downloading.RefreshObject(chooseObj);
                    foreach (var fileInfoLocalClass in chooseObj.DownloadingClass.Where(fileInfoLocalClass => null != fileInfoLocalClass.BackgroundWorker && fileInfoLocalClass.BackgroundWorker.IsBusy))
                        fileInfoLocalClass.BackgroundWorker.CancelAsync();
                    break;
                    case DownloadingStateEnum.BreakDownloading:
                    UserLocalFile.RemoveFileDownloadingBreakObject(chooseObj.FileGuid);
                    chooseObj.CurrentState = "正在重新连接....";
                    chooseObj.DownloadButton.Enabled = false;
                    chooseObj.DownloadButton.Text = "正在连接";
                    chooseObj.DownloadingState = DownloadingStateEnum.Downloading;
                    chooseObj.DownloadButton.Update();
                    Olv_Downloading.RemoveObject(chooseObj);
                    if (!File.Exists(chooseObj.FileLocalPath + GlobalVariable.FileTempExtension))
                    {
                        var messageStr = string.Format("数据文件 {0} 不存在，请检查后再重新下载!", chooseObj.FileName);
                        XtraMessageBox.Show(messageStr, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Olv_Downloading.RemoveObject(chooseObj);
                        _downloadingFileProgresses.Remove(chooseObj);
                        Olv_Uploading.Refresh();
                    }
                    else
                    {
                        chooseObj.DownloadButton.Text = "暂停下载";
                        chooseObj.DownloadButton.Update();
                        foreach (var fileInfoLocalClass in chooseObj.DownloadingClass.Where(x => x.FileOffset != x.FileEndOffset))
                        {
                            var downloadingWoker = new BackgroundWorker();
                            fileInfoLocalClass.BackgroundWorker = downloadingWoker;
                            downloadingWoker.DoWork +=downloadingWoker_DoWork;
                            downloadingWoker.WorkerSupportsCancellation = true;
                            downloadingWoker.RunWorkerAsync(fileInfoLocalClass);
                        }
                    }
                    break;
            }
        }
        #endregion

        #region Downloading Context Menum Event
        private void tsmi_DeleteDownloading_Click(object sender, EventArgs e)
        {
            tsmi_DeleteDownloading.Enabled = null != Olv_Downloading.SelectedItem;
            tsmi_DeleteDownloadingAll.Enabled = Olv_Downloading.Items.Count > 0;
        }

        private void tsmi_DeleteDownloadingAll_Click(object sender, EventArgs e)
        {
            if (null == Olv_Downloading.SelectedObject) return;
            var selectObj = Olv_Downloading.SelectedObject as DownloadingFileProgress;
            if (null == selectObj) return;
            if (selectObj.DownloadingState == DownloadingStateEnum.Downloading)
            {
                XtraMessageBox.Show("选中文件正在下载，请先暂停再删除!", GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (File.Exists(selectObj.FileLocalPath + GlobalVariable.FileTempExtension))
                File.Delete(selectObj.FileLocalPath + GlobalVariable.FileTempExtension);
            var delObj = _downloadingFileProgresses.FirstOrDefault(x => x.FileGuid.Equals(selectObj.FileGuid));
            if (null == delObj) return;
            _downloadingFileProgresses.Remove(delObj);
            UserLocalFile.RemoveFileDownloadingBreakObject(delObj.FileGuid);
            var tooBarItem = ToolBar_System.Items[ToolBarItemIndex.DownloadManager];
            tooBarItem.LeftUpNumber--;
        }

        private void cms_Downloading_Opening(object sender, CancelEventArgs e)
        {
            var tooBarItem = ToolBar_System.Items[ToolBarItemIndex.DownloadManager];
            var delObj = new List<DownloadingFileProgress>();
            foreach (DownloadingFileProgress del in Olv_Downloading.Objects)
            {
                if (del.DownloadingState == DownloadingStateEnum.Downloading) continue;
                if (File.Exists(del.FileLocalPath + GlobalVariable.FileTempExtension))
                    File.Delete(del.FileLocalPath + GlobalVariable.FileTempExtension);
                UserLocalFile.RemoveFileDownloadingBreakObject(del.FileGuid);
                delObj.Add(del);
                _downloadingFileProgresses.Remove(del);
            }
            foreach (var downloadFileProgress in delObj)
            {
                tooBarItem.LeftUpNumber--;
                Olv_Downloading.RemoveObject(downloadFileProgress);
            }
        }
        #endregion
    }

    #region Downloading Temp Object
    public class FileDoanloadingTemp
    {
        public string FileSid { get; set; }
        public string DownloadLocalPath { get; set; }
        public string FolderId { get; set; }
        public bool IsOpen { get; set; }
    }

    [Serializable]
    public enum DownloadingStateEnum
    {
        CreateConnectToServer = 0,
        Downloading = 1,
        BreakDownloading =2
    }

    [Serializable]
    public class DownloadingFileProgress
    {
        public string FileGuid { get; set; }
        public string FileName { get; set; }
        public string FileLocalPath { get; set; }
        public string ServerPath { get; set; }
        public string FolderId { get; set; }
        public DateTime BeginTime { get; set; }
        public DownloadingStateEnum DownloadingState { get; set; }
        public string CurrentState { get; set; }
        public long FileSize { get; set; }
        public double DisplaySize { get; set; }
        public SimpleButton DownloadButton { get; set; }
        public ProgressBarControl DownloadProgressBar { get; set; }
        public List<FileInfoLocalClass> DownloadingClass { get; set; }
        public bool IsOpen { get; set; }
        //占位
        public string Doing { get; set; }
        public string Progress { get; set; }
    }

    [Serializable]
    public class FileDownloadingBreakClass
    {
        public string FileGuid { get; set; }
        public string FileName { get; set; }
        public string FileLocalPath { get; set; }
        public string ServerPath { get; set; }
        public string FolderId { get; set; }
        public DateTime BeginTime { get; set; }
        public DownloadingStateEnum DownloadingState { get; set; }
        public string CurrentState { get; set; }
        public long FileSize { get; set; }
        public double DisplaySize { get; set; }
        public List<FileDownloadingBreakBlockClass> FileDownloadingBreakBlockClasses { get; set; }
        public int MaxProgress { get; set; }
        public int ValueProgress { get; set; }
    }

    [Serializable]
    public class FileDownloadingBreakBlockClass
    {
        public string FileGuid { get; set; }
        public string LocalPath { get; set; }
        public long TransferLength { get; set; }
        public long FileOffset { get; set; } //开始位置
        public long FileEndOffset { get; set; }//结束位置
        public string FileServerPath { get; set; }
    }
#endregion
}